<template>
  <el-form
    :model="form"
    label-width="100px"
    size="small"
    ref="formRef"
    :rules="rules"
  >
    <el-form-item label="学号">
      <el-input v-model="form.studentId" maxlength="15" disabled />
    </el-form-item>
    <el-form-item label="姓名" prop="name">
      <el-input v-model="form.name" />
    </el-form-item>
    <el-form-item label="性别" prop="gender">
      <el-radio-group v-model="form.gender">
        <el-radio label="M">男</el-radio>
        <el-radio label="F">女</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="年级" prop="gradeYear">
      <el-select v-model="form.gradeYear" placeholder="请选择年级">
        <el-option label="研二" value="2" />
        <el-option label="研三" value="3" />
      </el-select>
    </el-form-item>
    <el-form-item label="学院" prop="college">
      <el-input v-model="form.college" />
    </el-form-item>
    <el-form-item label="专业" prop="department">
      <el-input v-model="form.department" />
    </el-form-item>
    <el-form-item label="学籍状态" prop="status">
      <el-select v-model="form.status" placeholder="请选择学籍状态">
        <el-option label="在读" value="在读" />
        <el-option label="休学" value="休学" />
        <el-option label="毕业" value="毕业" />
      </el-select>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="handleUpdate">保存更新</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { getStudentInfo, getStudentId } from '@/utils/studentInfo.js'

export default {
  name: 'PersonalForm',
  data() {
    return {
      form: {
        studentId: '',
        name: '',
        gender: 'M',
        gradeYear: '',
        college: '',
        department: '',
        status: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { pattern: /^[\u4e00-\u9fa5]+$/, message: '姓名只能输入汉字', trigger: 'blur' }
        ],
        gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
        gradeYear: [{ required: true, message: '请选择年级', trigger: 'change' }],
        college: [
          { required: true, message: '请输入学院', trigger: 'blur' },
          { pattern: /^[\u4e00-\u9fa5]+$/, message: '只能输入汉字', trigger: 'blur' }
        ],
        department: [
          { required: true, message: '请输入专业', trigger: 'blur' },
          { pattern: /^[\u4e00-\u9fa5]+$/, message: '只能输入汉字', trigger: 'blur' }
        ],
        status: [{ required: true, message: '请选择学籍状态', trigger: 'change' }]
      }
    }
  },
  mounted() {
    this.loadStudentInfo()
  },
  methods: {
    async loadStudentInfo() {
     
      const studentInfo = getStudentInfo()
      
      if (studentInfo) {
      
        this.form = {
          studentId: studentInfo.studentId || '',
          name: studentInfo.name || '',
          gender: studentInfo.gender || 'M',
          gradeYear: studentInfo.gradeYear ? String(studentInfo.gradeYear) : '',
          college: studentInfo.college || '',
          department: studentInfo.department || '',
          status: studentInfo.status || ''
        }
        return
      }

      
      const studentId = getStudentId()
      if (!studentId) {
        ElMessage.error('未检测到登录学号，请重新登录')
        return
      }

      try {
        const res = await axios.get(`/api/students/${studentId}`, {
          withCredentials: true
        })
        if (res.data) {
          this.form = {
            studentId: res.data.studentId || studentId,
            name: res.data.name || '',
            gender: res.data.gender || 'M',
            gradeYear: res.data.gradeYear ? String(res.data.gradeYear) : '',
            college: res.data.college || '',
            department: res.data.department || '',
            status: res.data.status || ''
          }
        } else {
          ElMessage.warning('未找到学生信息')
        }
      } catch (error) {
        console.error('获取学生信息失败', error)
        ElMessage.error('获取学生信息失败，请稍后重试')
      }
    },

    handleUpdate() {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) {
          ElMessage.error('请检查填写项，修正错误后重试')
          return
        }
        try {
          const res = await axios.put('/api/students', this.form, {
            headers: { 'Content-Type': 'application/json' },
            withCredentials: true
          })

          if (res.data > 0 || res.data.code === 200) {
            ElMessage.success('学生信息更新成功')
            
           
            const studentInfo = getStudentInfo()
            if (studentInfo) {
              const updatedStudentInfo = {
                ...studentInfo,
                name: this.form.name,
                gender: this.form.gender,
                gradeYear: this.form.gradeYear,
                college: this.form.college,
                department: this.form.department,
                status: this.form.status
              }
              localStorage.setItem('studentInfo', JSON.stringify(updatedStudentInfo))
            }
          } else {
            ElMessage.error(res.data.message || '更新失败')
          }
        } catch (error) {
          console.error('更新失败:', error)
          ElMessage.error('更新请求失败，请稍后重试')
        }
      })
    }
  }
}
</script>

<style scoped></style>
